<template>
  <div class="community-list-container">
    <div class="fixed-header">
      <div class="page-header">
        <h3>社区管理</h3>
        <div class="search-group">
          <!-- 姓名搜索 -->
          <el-input
              v-model="searchParams.name"
              placeholder="请输入名称"
              clearable
              style="width: 200px"
          />

          <!-- 地址搜索 -->
          <el-input
              v-model="searchParams.address"
              placeholder="请输入地址"
              clearable
              style="width: 200px"
          />


          <!-- 电话搜索 -->
          <el-input
              v-model="searchParams.phone"
              placeholder="请输入电话"
              clearable
              style="width: 200px"
          />

          <!-- 搜索按钮 -->
          <el-button type="primary" @click="handleSearch">搜索</el-button>

          <!-- 重置按钮 -->
          <el-button @click="resetSearch">重置</el-button>
        </div>
        <div class="header-buttons">
          <el-button type="info" :icon="Document" @click="handleManageCheckTypes">管理检查类型</el-button>
          <el-button type="primary" :icon="Plus" @click="handleAdd">添加社区</el-button>
        </div>
      </div>
    </div>

    <el-table
        :data="communities"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
        row-class-name="table-row"
    >
      <el-table-column prop="name" label="社区名称" align="center" min-width="120"/>
      <el-table-column prop="address" label="地址" align="center" min-width="200"/>
      <el-table-column prop="phone" label="联系电话" align="center" min-width="150"/>
      <el-table-column label="医生数量" width="100" align="center">
        <template #default="{ row }">
          {{ row.doctors?.length || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="老年人数量" width="100" align="center">
        <template #default="{ row }">
          {{ row.elders?.length || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="子女数量" width="100" align="center">
        <template #default="{ row }">
          {{ row.children?.length || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="400" fixed="right" class-name="table-actions">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" :icon="List" size="small" @click="handleManageActions(row)">管理活动</el-button>
          <el-button type="danger" :icon="Delete" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑社区对话框 -->
    <CommunityFormDialog
        v-model="dialogVisible"
        :community="currentCommunity"
        :is-edit="dialogType === 'edit'"
        @success="fetchCommunityList"
    />

    <!-- 管理活动对话框 -->
    <el-dialog
        title="管理活动"
        v-model="actionDialogVisible"
        width="1400px"
        :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <div class="table-header">
          <h3>活动列表</h3>
          <el-button type="primary" :icon="Plus" @click="handleAddAction">添加活动</el-button>
        </div>
        <el-table :data="actions" border stripe>
          <el-table-column prop="actionName" label="活动名称" align="center" min-width="120"/>
          <el-table-column prop="actionContext" label="活动内容" align="center" min-width="200"
          />
          <el-table-column prop="actionTime" label="活动时间" align="center" min-width="150"/>
          <el-table-column label="操作" width="200" align="center" fixed="right" class-name="table-actions">
            <template #default="{ row }">
              <el-button type="primary" :icon="Edit" size="small" @click="handleEditAction(row)">编辑</el-button>
              <el-button type="danger" :icon="Delete" size="small" @click="handleDeleteAction(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="actionDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加/编辑活动对话框 -->
    <ActionFormDialog
        v-model="actionFormVisible"
        :action="currentAction"
        :is-edit="actionDialogType === 'edit'"
        :community-id="currentCommunity?.id || 0"
        @success="handleManageActions(currentCommunity!)"
    />

    <!-- 管理检查类型对话框 -->
    <el-dialog
        v-model="checkTypeDialogVisible"
        width="1200px"
        :close-on-click-modal="false"
    >
      <template #header>
        <div class="dialog-header">
          <span>管理检查类型</span>
          <el-button type="primary" :icon="Plus" @click="handleAddCheckType">添加检查类型</el-button>
        </div>
      </template>
      <div class="dialog-content">
        <el-table :data="checkTypes" border stripe>
          <el-table-column prop="id" label="ID" width="80" align="center"/>
          <el-table-column prop="name" label="名称" align="center" min-width="120"/>
          <el-table-column prop="context" label="内容" align="center" min-width="400" show-overflow-tooltip/>
          <el-table-column label="操作" width="200" align="center" fixed="right" class-name="table-actions">
            <template #default="{ row }">
              <el-button type="primary" :icon="Edit" @click="handleEditCheckType(row)">编辑</el-button>
              <el-button type="danger" :icon="Delete" @click="handleDeleteCheckType(row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checkTypeDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加/编辑检查类型对话框 -->
    <CheckTypeFormDialog
        v-model="checkTypeFormVisible"
        :check-type="currentCheckType"
        :is-edit="checkTypeDialogType === 'edit'"
        @success="handleManageCheckTypes"
    />
  </div>
</template>

<script setup lang="ts">
import {onActivated, onMounted, ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Delete, Document, Edit, List, Plus} from '@element-plus/icons-vue'
import type {Community} from '@/types/community'
import type {Action} from '@/types/action'
import type {CheckType} from '@/types/checkType'
import {
  deleteCommunity,
  getAllCommunities,
  getCommunityChildren,
  getCommunityDoctors,
  getCommunityElders
} from '@/api/community'
import {deleteAction, getActionList} from '@/api/action'
import {deleteCheckType, getAllCheckTypes} from '@/api/checkType'
import CommunityFormDialog from './components/CommunityFormDialog.vue'
import ActionFormDialog from './components/ActionFormDialog.vue'
import CheckTypeFormDialog from './components/CheckTypeFormDialog.vue'

// 数据
const communities = ref<Community[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const currentCommunity = ref<Community | null>(null)

// 活动管理
const actionDialogVisible = ref(false)
const actionFormVisible = ref(false)
const actionDialogType = ref<'add' | 'edit'>('add')
const currentAction = ref<Action | null>(null)
const actions = ref<Action[]>([])

// 检查类型管理
const checkTypeDialogVisible = ref(false)
const checkTypeFormVisible = ref(false)
const checkTypeDialogType = ref<'add' | 'edit'>('add')
const currentCheckType = ref<CheckType | null>(null)
const checkTypes = ref<CheckType[]>([])

// 新增数据
const searchParams = ref({
  name: '',
  address: '',
  phone: ''
})

// 获取社区列表
const fetchCommunityList = async () => {
  loading.value = true
  try {
    const communitiesData = await getAllCommunities(
        {
          name: searchParams.value.name,
          address: searchParams.value.address,
          phone: searchParams.value.phone
        }
    )
    communities.value = await Promise.all(
        communitiesData.map(async (community: Community) => {
          const [doctors, elders, children] = await Promise.all([
            getCommunityDoctors(community.id),
            getCommunityElders(community.id),
            getCommunityChildren(community.id)
          ])

          return {
            ...community,
            doctors: doctors || [],
            elders: elders || [],
            children: children || []
          }
        })
    )
  } catch (error) {
    console.error('获取社区列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  fetchCommunityList();
}

// 重置搜索
const resetSearch = () => {
  searchParams.value = {
    name: '',
    address: '',
    phone: '',
  };
  fetchCommunityList();
}

// 添加社区
const handleAdd = () => {
  dialogType.value = 'add'
  currentCommunity.value = null
  dialogVisible.value = true
}

// 编辑社区
const handleEdit = (row: Community) => {
  dialogType.value = 'edit'
  currentCommunity.value = row
  dialogVisible.value = true
}

// 删除社区
const handleDelete = async (row: Community) => {
  try {
    await ElMessageBox.confirm('删除后将无法恢复该社区的所有信息，包括活动信息，是否确认删除？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
      closeOnClickModal: false
    })
    await deleteCommunity(row)
    ElMessage.success('删除成功')
    await fetchCommunityList()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    }
  }
}

// 管理活动
const handleManageActions = async (row: Community) => {
  currentCommunity.value = row
  actionDialogVisible.value = true
  try {
    actions.value = await getActionList({communityId: row.id})
  } catch (error) {
    console.error('获取活动列表失败:', error)
  }
}

// 添加活动
const handleAddAction = () => {
  actionDialogType.value = 'add'
  currentAction.value = null
  actionFormVisible.value = true
}

// 编辑活动
const handleEditAction = (row: Action) => {
  actionDialogType.value = 'edit'
  currentAction.value = row
  actionFormVisible.value = true
}

// 删除活动
const handleDeleteAction = async (row: Action) => {
  try {
    await ElMessageBox.confirm('确定要删除该活动吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await deleteAction(row)
    ElMessage.success('删除成功')
    await handleManageActions(currentCommunity.value!)
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    }
  }
}

// 检查类型管理
const handleManageCheckTypes = async () => {
  checkTypeDialogVisible.value = true
  try {
    checkTypes.value = await getAllCheckTypes()
  } catch (error) {
    console.error('获取检查类型列表失败:', error)
  }
}

// 添加检查类型
const handleAddCheckType = () => {
  checkTypeDialogType.value = 'add'
  currentCheckType.value = null
  checkTypeFormVisible.value = true
}

// 编辑检查类型
const handleEditCheckType = (row: CheckType) => {
  checkTypeDialogType.value = 'edit'
  currentCheckType.value = row
  checkTypeFormVisible.value = true
}

// 删除检查类型
const handleDeleteCheckType = async (row: CheckType) => {
  try {
    await ElMessageBox.confirm('确定要删除该检查类型吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await deleteCheckType(row.id)
    ElMessage.success('删除成功')
    await handleManageCheckTypes()
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除')
    }
  }
}

onActivated(async () => {
  await fetchCommunityList()
})
</script>

<style scoped>
.community-list-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 95%;
}

.fixed-header {
  flex-shrink: 0;
  padding-bottom: 20px;
  background-color: #fff;
  z-index: 1;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
  color: #303133;
}

.search-group {
  display: flex;
  align-items: center;
  gap: 10px; /* 统一设置元素间间距 */
}

/* 统一输入框和按钮的宽度和间距 */
.search-group .el-input,
.search-group .el-select,
.search-group .el-button {
  margin: 0; /* 清除默认margin */
}

.header-buttons {
  display: flex;
  gap: 10px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table--border) {
  border: 1px solid #ebeef5;
}

:deep(.el-table--border th),
:deep(.el-table--border td) {
  border-right: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-button) {
  min-width: 80px;
  height: 32px;
  padding: 6px 12px;
  font-size: 14px;
}

:deep(.el-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-avatar) {
  border: 2px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Dialog styles */
:deep(.el-dialog__header) {
  margin: 0;
  padding: 20px 30px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.el-dialog__footer) {
  padding: 20px 30px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.dialog-content {
  padding: 0 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-container {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 操作按钮统一间距 */
:deep(.table-actions .cell) {
  gap: 8px;
}
</style>